package net.sureon.web.system;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sureon.biz.CompanyBO;
import net.sureon.biz.CompanyMgr;
import net.sureon.common.SureonConstants;
import net.sureon.common.exception.SureonException;
import net.sureon.dao.Company;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.mvc.SimpleFormController;

@SuppressWarnings("unchecked")
public class ManageCustomer extends SimpleFormController implements Controller {
	private static final Log logger = LogFactory.getLog(ManageCustomer.class);
	private CompanyMgr companyMgr;

	/**
	 * @return the companyMgr
	 */
	public CompanyMgr getCompanyMgr() {
		return companyMgr;
	}

	/**
	 * @param companyMgr the companyMgr to set
	 */
	public void setCompanyMgr(CompanyMgr companyMgr) {
		this.companyMgr = companyMgr;
	}

	private static final String ATTRI_CUSTOMERS = "customers";
	private static final String ACTION = "action";
	private static final String ID = "customerID";
	private static final String ATTRI_CUSTOMERFORM = "customerForm";
	private static final String PARAM_VIEW = "view";
	private static final String SELLER_DORP_DOWN_DISPLAY_LIST = "SellerDropDownDisplayList";

	protected Map referenceData(HttpServletRequest request, Object command,
			Errors errors) throws Exception {
		Map result = new HashMap();
		String action = request.getParameter(ACTION);
		String customerID = request.getParameter(ID);
		String customerInfo = request.getParameter(PARAM_VIEW);
		CustomerForm customerForm = (CustomerForm)command;
		if("customer".equals(customerInfo)) {
			result.put(ATTRI_CUSTOMERS, buildCustomerInfoListResult());
			customerForm.setView("customer");
		} else {
			result.put(ATTRI_CUSTOMERS, buildPotentialCustomerListResult());
			customerForm.setView("potential");
		}
		if (action != null && customerID != null) {
			processStandaloneAction(command, action, customerID);
			((CustomerForm)command).setView(customerInfo);
		}
		customerForm.setCompanyTypeList(buildCompanyTypeListResult());
		customerForm.setCompanyStatusList(buildCompanyStatusListResult());
		result.put(ATTRI_CUSTOMERFORM, customerForm);
		return result;
	}
	
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		CustomerForm customerForm = (CustomerForm)command;
		if(customerForm.getCompanyID() > 0) {
			long companyID = customerForm.getCompanyID();
			CompanyBO company = companyMgr.getCompany(companyID);
			updateCustomer(company, customerForm);
		} else {
			createCustomer(customerForm);
			customerForm.reset();
		}
		
		String url = request.getParameter("view");
		ModelAndView view = new ModelAndView(this.getSuccessView());
		Map result = new HashMap();
		if("customer".equals(url)) {
			// 列出全部的潜在客户信息
			result.put(ATTRI_CUSTOMERS, buildCustomerInfoListResult());
			customerForm.setView("customer");
		} else {
			// 列出正式客户信息
			result.put(ATTRI_CUSTOMERS, buildPotentialCustomerListResult());
			customerForm.setView("potential");
		}
		customerForm.setCompanyTypeList(buildCompanyTypeListResult());
		customerForm.setCompanyStatusList(buildCompanyStatusListResult());
		result.put(ATTRI_CUSTOMERFORM, customerForm);
		view.addAllObjects(result);
		return view;
	}
	
	/**
	 * @return 潜在客户列表 
	 */
	private List<CompanyBO> buildPotentialCustomerListResult() {
		List<CompanyBO> list = null;
		list = companyMgr.getCustomerByStatus(SureonConstants.CUSTOMER_STATUS_POTENTIAL);
		if(list == null) {
			return new ArrayList<CompanyBO>();
		}
		return list;
	}
	
	/**
	 * @return 正式客户列表
	 */
	private List<CompanyBO> buildCustomerInfoListResult() {
		List<CompanyBO> list = null;
		list = companyMgr.getCustomerByStatus(SureonConstants.CUSTOMER_STATUS_CUSTOMER);
		if(list == null) {
			return new ArrayList<CompanyBO>();
		}
		return list;
	}

	private void processStandaloneAction(Object command, String action,
			String id) throws Exception {
		long customerID = Long.parseLong(id);
		if("edit".equals(action)) {
			// 进行编辑 
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			CustomerForm form = (CustomerForm)command;
			CompanyBO company = companyMgr.getCompany(customerID);
			form.setCompanyID(company.getCompanyID());
			form.setCompanyFullName(company.getCompanyVO().getCompanyFullName());
			form.setSiteURL(company.getCompanyVO().getSiteURL());
			form.setCompanyAddress(company.getCompanyVO().getCompanyAddress());
			form.setCompanyType(company.getCompanyVO().getCompanyType());
			form.setCompanyWebSite(company.getCompanyVO().getCompanyWebSite());
			form.setCompanyZipCode(company.getCompanyVO().getCompanyZipCode());
			form.setHrAddress(company.getCompanyVO().getHRAddress());
			form.setHrEmail(company.getCompanyVO().getHREmail());
			form.setHrFax(company.getCompanyVO().getHRFax());
			form.setHrName(company.getCompanyVO().getHRName());
			form.setHrTel(company.getCompanyVO().getHRTel());
			form.setAdminAddress(company.getCompanyVO().getAdminAddress());
			form.setAdminEmail(company.getCompanyVO().getAdminEmail());
			form.setAdminFax(company.getCompanyVO().getAdminFax());
			form.setAdminName(company.getCompanyVO().getAdminName());
			form.setAdminTel(company.getCompanyVO().getAdminTel());
			form.setIndustry(company.getCompanyVO().getIndustry());
			form.setSeller(company.getCompanyVO().getSeller());
			
			form.setCompanyStatus(company.getCompanyVO().getCompanyStatus());
			
			form.setRegisterDate(sdf.format(company.getCompanyVO().getRegisterDate()));
			form.setValidDate(sdf.format(company.getCompanyVO().getValidDate()));
			
			int totalUserNum = companyMgr.getCompanyConsumeStatus(company.getCompanyID(), new Date()).getTotalUserNumber();
			
			form.setEmployeeNum(totalUserNum);
		}
		else {
			CustomerForm form = (CustomerForm)command;
			createCustomer(form);
		}
	}
	private void createCustomer(CustomerForm form) throws Exception {
		// 判断该siteURL是否已经被使用 
		Company vo = new Company();
		String siteURL = form.getSiteURL();
		CompanyBO companyBO = null;
		try {
			companyBO = companyMgr.getCompany(siteURL);
		} catch(Exception e) {
			logger.warn("the company is not exists, siteURL = " + siteURL);
		}
		if(companyBO != null) {
			logger.error("the siteURL is duplicated, siteURL = " + siteURL);
			throw new SureonException("siteurl_duplicated");
		}
		vo.setSiteURL(siteURL);
		vo.setCompanyAddress(form.getCompanyAddress());
		vo.setCompanyFullName(form.getCompanyFullName());
		
		vo.setCompanyStatus(form.getCompanyStatus());
		
		vo.setCompanyType(form.getCompanyType());
		vo.setCompanyWebSite(form.getCompanyWebSite());
		vo.setCompanyZipCode(form.getCompanyZipCode());
		vo.setHRAddress(form.getHrAddress());
		vo.setHREmail(form.getHrEmail());
		vo.setHRFax(form.getHrFax());
		vo.setHRName(form.getHrName());
		vo.setHRTel(form.getHrTel());
		vo.setAdminAddress(form.getAdminAddress());
		vo.setAdminEmail(form.getAdminEmail());
		vo.setAdminFax(form.getAdminFax());
		vo.setAdminName(form.getAdminName());
		vo.setAdminTel(form.getAdminTel());
		vo.setSeller(form.getSeller());
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			vo.setRegisterDate(sdf.parse(form.getRegisterDate()));
		} catch(Exception e) {
			logger.warn("the custormer register date is null in create customer information");
			throw new SureonException("date_format_not_allow");
		}
		try {
			vo.setValidDate(sdf.parse(form.getValidDate()));
		} catch(Exception e) {
			logger.warn("the customer validdate is null in create customer information");
			throw new SureonException("date_format_not_allow");
		}
		
		
		vo.setIndustry(form.getIndustry());
		vo.setCompanyStatus(form.getCompanyStatus());
		
		CompanyBO company = new CompanyBO(vo);
		companyMgr.insertCompany(company);
	}
	private void updateCustomer(CompanyBO company, CustomerForm form) throws Exception {
		Company vo = company.getCompanyVO();
		if(!company.getCompanyVO().getSiteURL().equals(form.getSiteURL())) {
			CompanyBO companyBO = null;
			try {
				companyBO = companyMgr.getCompany(form.getSiteURL());
			} catch(Exception e) {
				logger.warn("the company is not exists, siteURL = " + form.getSiteURL());
			}
			if(companyBO != null) {
				logger.error("this siteURL is duplicated, siteURL = " + form.getSiteURL()) ;
				throw new SureonException("siteurl_duplicated");
			}
		}
		vo.setSiteURL(form.getSiteURL());
		vo.setCompanyAddress(form.getCompanyAddress());
		vo.setCompanyFullName(form.getCompanyFullName());
		vo.setCompanyStatus(form.getCompanyStatus());
		vo.setCompanyType(form.getCompanyType());
		vo.setCompanyWebSite(form.getCompanyWebSite());
		vo.setCompanyZipCode(form.getCompanyZipCode());
		vo.setHRAddress(form.getHrAddress());
		vo.setHREmail(form.getHrEmail());
		vo.setHRFax(form.getHrFax());
		vo.setHRName(form.getHrName());
		vo.setHRTel(form.getHrTel());
		vo.setAdminAddress(form.getAdminAddress());
		vo.setAdminEmail(form.getAdminEmail());
		vo.setAdminFax(form.getAdminFax());
		vo.setAdminName(form.getAdminName());
		vo.setAdminTel(form.getAdminTel());
		vo.setSeller(form.getSeller());
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			vo.setRegisterDate(sdf.parse(form.getRegisterDate()));
		} catch(Exception e) {
			logger.warn("the custormer register date is null in update customer information");
			throw new SureonException("date_format_not_allow");
		}
		try {
			vo.setValidDate(sdf.parse(form.getValidDate()));
		} catch(Exception e) {
			logger.warn("the customer validdate is null in update customer information");
			throw new SureonException("date_format_not_allow");
		}
		vo.setIndustry(form.getIndustry());
		vo.setCompanyStatus(form.getCompanyStatus());
		
		companyMgr.updateCompany(company);
	}
	
	private List<CompanyTypeDropDownDisplay> buildCompanyTypeListResult() {
		List<CompanyTypeDropDownDisplay> list = new ArrayList<CompanyTypeDropDownDisplay>();
		list.add(new CompanyTypeDropDownDisplay("overseas_investment_us", "外资（欧美）"));
		list.add(new CompanyTypeDropDownDisplay("overseas_investment_not_us", "外资（非欧美）"));
		list.add(new CompanyTypeDropDownDisplay("joint_venture_us", "合资（欧美）"));
		list.add(new CompanyTypeDropDownDisplay("joint_venture_not_us", "合资（非欧美）"));
		list.add(new CompanyTypeDropDownDisplay("country_corporation", "国企/上市公司"));
		list.add(new CompanyTypeDropDownDisplay("people_manage", "民营/私营企业"));
		list.add(new CompanyTypeDropDownDisplay("other_country_delegate", "外企代表处"));
		list.add(new CompanyTypeDropDownDisplay("other_property", "其他性质"));
		return list;
	}
	
	private List<CompanyStatusDropDownDisplay> buildCompanyStatusListResult() {
		List<CompanyStatusDropDownDisplay> list = new ArrayList<CompanyStatusDropDownDisplay>();
		list.add(new CompanyStatusDropDownDisplay("do_not_contacted", "尚未接触"));
		list.add(new CompanyStatusDropDownDisplay("linked", "已经联系"));
		list.add(new CompanyStatusDropDownDisplay("not_tested_at_present", "暂不试用"));
		list.add(new CompanyStatusDropDownDisplay("application_trial", "申请试用"));
		list.add(new CompanyStatusDropDownDisplay("trial_in_now", "正在试用"));
		list.add(new CompanyStatusDropDownDisplay("not_cooperate_at_present", "暂不合作"));
		list.add(new CompanyStatusDropDownDisplay("customer", "正式客户"));
		return list;
	}
	

	private static class CompanyTypeDropDownDisplay {
		private String typeShortName;
		private String typeFullName;
		private CompanyTypeDropDownDisplay(String type, String typeName) {
			this.typeShortName = type;
			this.typeFullName = typeName;
		}
		public String getTypeShortName() {
			return typeShortName;
		}
		public void setTypeShortName(String typeShortName) {
			this.typeShortName = typeShortName;
		}
		public String getTypeFullName() {
			return typeFullName;
		}
		public void setTypeFullName(String typeFullName) {
			this.typeFullName = typeFullName;
		}
	}
	
	private static final class CompanyStatusDropDownDisplay {
		private String statusValue;
		private String statusDisplayName;
		private CompanyStatusDropDownDisplay(String statusvalue, String statusDisplayName) {
			this.statusValue = statusvalue;
			this.statusDisplayName = statusDisplayName;
		}
		public String getStatusValue() {
			return statusValue;
		}
		public void setStatusValue(String statusValue) {
			this.statusValue = statusValue;
		}
		public String getStatusDisplayName() {
			return statusDisplayName;
		}
		public void setStatusDisplayName(String statusDisplayName) {
			this.statusDisplayName = statusDisplayName;
		}
	}
	
}
